<template>
  <!-- 搜索工作栏 -->
  <ContentWrap>
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="部门名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入部门名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="部门状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择部门状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['system:dept:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button type="danger" plain @click="toggleExpandAll">
          <Icon icon="ep:sort" class="mr-5px" /> 展开/折叠
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      row-key="id"
      :default-expand-all="isExpandAll"
      v-if="refreshTable"
      @row-click="handleRowClick"
    >
      <el-table-column prop="name" label="部门名称" />
      <el-table-column prop="leader" label="负责人">
        <template #default="scope">
          {{ userList.find((user) => user.id === scope.row.leaderUserId)?.nickname }}
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序" />
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="今日数据" align="center" width="100">
        <template #default="scope">
          <el-tag type="success">{{ scope.row.todayCount }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="总数据" align="center" width="100">
        <template #default="scope">
          <el-tag type="info">{{ scope.row.totalCount }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template #default="{ row }">
          {{ formatDate(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['system:dept:update']"
          >
            修改
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['system:dept:delete']"
          >
            删除
          </el-button>
          <el-button
            link
            type="primary"
            @click="handleRowClick(scope.row)"
          >
            查看线索
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <DeptForm ref="formRef" @success="getList" />

  <!-- 线索数据弹窗 -->
  <el-dialog
    v-model="leadsDialogVisible"
    title="线索数据"
    width="80%"
    destroy-on-close
  >
    <div v-loading="leadsLoading">
      <!-- 统计信息 -->
      <el-row class="mb-4">
        <el-col :span="12">
          <span class="font-bold">今日数据总数：</span>
          <span class="text-primary">{{ leadsData.todayCount }}</span>
        </el-col>
        <el-col :span="12">
          <span class="font-bold">历史数据总数：</span>
          <span class="text-primary">{{ leadsData.totalCount }}</span>
        </el-col>
      </el-row>

      <!-- 线索列表 -->
      <el-table :data="leadsData.leads" stripe>
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column prop="phone" label="电话" width="120" />
        <el-table-column prop="city" label="城市" width="120" />
        <el-table-column prop="source" label="来源" width="150" />
        <el-table-column prop="notes" label="备注" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">
              {{ row.status === 1 ? '正常' : '关闭' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120">
          <template #default>
            <el-button
              link
              type="success"
              @click="handleAutoAssign"
            >
              自动分配
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </el-dialog>

  <!-- 自动分配报告弹窗 -->
  <el-dialog
    v-model="assignReportVisible"
    title="自动分配报告"
    width="800px"
    destroy-on-close
  >
    <div class="whitespace-pre-wrap font-mono">{{ assignReport }}</div>
    <template #footer>
      <el-button type="primary" @click="assignReportVisible = false">确定</el-button>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { formatDate } from '@/utils/formatTime'
import { handleTree } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import DeptForm from './DeptForm.vue'
import * as UserApi from '@/api/system/user'
import request from '@/config/axios'

defineOptions({ name: 'SystemDept' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref() // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 100,
  name: undefined,
  status: undefined
})
const queryFormRef = ref() // 搜索的表单
const isExpandAll = ref(true) // 是否展开，默认全部展开
const refreshTable = ref(true) // 重新渲染表格状态
const userList = ref<UserApi.UserVO[]>([]) // 用户列表

// 线索数据相关
const leadsDialogVisible = ref(false)
const leadsLoading = ref(false)
const leadsData = ref({
  deptName: '',
  leads: [],
  todayCount: 0,
  totalCount: 0
})

// 自动分配相关
const assignReportVisible = ref(false)
const assignReport = ref('')

// 收集所有部门ID
const collectDeptIds = (departments: any[]): number[] => {
  let ids: number[] = []
  if (!Array.isArray(departments)) return ids
  
  for (const dept of departments) {
    ids.push(dept.id)
    if (dept.children && dept.children.length > 0) {
      ids = [...ids, ...collectDeptIds(dept.children)]
    }
  }
  return ids
}

// 将数据映射到部门树
const updateDeptData = (departments: any[], deptDataMap: Record<number, { todayCount: number; totalCount: number }>) => {
  if (!Array.isArray(departments)) return
  
  for (const dept of departments) {
    const deptData = deptDataMap[dept.id]
    if (deptData) {
      dept.todayCount = deptData.todayCount || 0
      dept.totalCount = deptData.totalCount || 0
    } else {
      dept.todayCount = 0
      dept.totalCount = 0
    }
    
    if (dept.children && dept.children.length > 0) {
      updateDeptData(dept.children, deptDataMap)
    }
  }
}

/** 查询部门列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await DeptApi.getDeptPage(queryParams)
    const deptList = handleTree(data)
    
    // 获取所有部门ID
    const deptIds = collectDeptIds(deptList)
    
    // 批量获取部门数据
    try {
      const response = await request.post({ 
        url: '/weiyi/leads/batch-get',
        headers: {
          'Content-Type': 'application/json'
        },
        data: {
          ids: deptIds
        }
      })
      
      // 创建部门数据映射
      const deptDataMap: Record<number, { todayCount: number; totalCount: number }> = {}
      if (response && Array.isArray(response)) {
        response.forEach((item: any) => {
          deptDataMap[item.deptId] = {
            todayCount: item.todayCount || 0,
            totalCount: item.totalCount || 0
          }
        })
      }
      
      // 更新部门树数据
      updateDeptData(deptList, deptDataMap)
    } catch (error) {
      console.error('批量获取部门数据失败:', error)
    }
    
    list.value = deptList
  } finally {
    loading.value = false
  }
}

/** 展开/折叠操作 */
const toggleExpandAll = () => {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  nextTick(() => {
    refreshTable.value = true
  })
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.pageNo = 1
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await DeptApi.deleteDept(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 处理行点击事件 */
const handleRowClick = async (row) => {
  leadsDialogVisible.value = true
  leadsLoading.value = true
  try {
    const response = await request.get({ 
      url: '/weiyi/leads/get-by-dept',
      params: { deptId: row.id }
    })
    
    // 检查响应数据是否包含必要的字段
    if (response && response.leads && Array.isArray(response.leads)) {
      leadsData.value = {
        deptName: response.deptName || '',
        leads: response.leads,
        todayCount: response.todayCount || 0,
        totalCount: response.totalCount || 0
      }
    } else {
      message.error('获取线索数据失败：数据格式不正确')
      // 重置数据为默认值
      leadsData.value = {
        deptName: '',
        leads: [],
        todayCount: 0,
        totalCount: 0
      }
    }
  } catch (error: any) {
    console.error('获取线索数据失败:', error)
    message.error('获取线索数据失败：' + (error?.message || '未知错误'))
    // 重置数据为默认值
    leadsData.value = {
      deptName: '',
      leads: [],
      todayCount: 0,
      totalCount: 0
    }
  } finally {
    leadsLoading.value = false
  }
}

/** 处理自动分配 */
const handleAutoAssign = async () => {
  try {
    const response = await request.post({ 
      url: '/weiyi/leads/auto-assign'
    })
    
    if (response) {
      assignReport.value = response
      assignReportVisible.value = true
      // 刷新列表以更新数据
      await getList()
      message.success('自动分配完成')
    } else {
      message.error('自动分配失败：未收到响应数据')
    }
  } catch (error: any) {
    console.error('自动分配失败:', error)
    message.error('自动分配失败：' + (error?.message || '未知错误'))
  }
}

/** 初始化 **/
onMounted(async () => {
  await getList()
  // 获取用户列表
  userList.value = await UserApi.getSimpleUserList()
})
</script>

<style scoped>
.whitespace-pre-wrap {
  white-space: pre-wrap;
}

.font-mono {
  font-family: monospace;
}
</style>
